//
//  CTVerificationLogic.m
//  ConstellationTalk_0.1
//
//  Created by riley on 15/4/22.
//  Copyright (c) 2015年 riley chu. All rights reserved.
//

#import "CTVerificationLogic.h"
#import "CTDebugManager.h"
#import "CTUrl.h"
#import "CTRequestUtil.h"
#import <SMS_SDK/SMS_SDK.h>
#import "CTFile.h"

#define CT_VERIFICATIONVIEW_TIME_INTERVAL 1.2
#define CT_VERIFICATIONVIEW_TIME_COUNTDOWN 60


@interface CTVerificationLogic ()
{
    NSTimer * countTimer;
    int countTime;
}

@end


@implementation CTVerificationLogic
@synthesize delegate;


- (void)dealloc
{
    
}

-(void)deallocVerficationLogic{
    [countTimer invalidate];
    countTimer = nil;
    [CTDebugManager showDebugLogInfo:@"dealloc : CTVerificationLogic Is Removed!!!"];
    
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}


#pragma mark - timer

-(void)verificationTimerStatrt:(NSString *)phoneNumber area:(NSString *)zone
{
    if (countTimer == nil) {
        
        countTime = CT_VERIFICATIONVIEW_TIME_COUNTDOWN;
        
        countTimer = [NSTimer scheduledTimerWithTimeInterval:CT_VERIFICATIONVIEW_TIME_INTERVAL target:self selector:@selector(timerCountDown:) userInfo:nil repeats:YES];
        [countTimer fire];
        
        [CTDebugManager showDebugLogInfo:@"获取验证码timer启动"];
        
        if ([self.delegate respondsToSelector:@selector(sendMessageSuccess:)]) {
            [self.delegate sendMessageSuccess:self];
        }
        
        [self sendSmsMessage:phoneNumber area:zone];
    }
}

-(void)timerCountDown:(id)sender
{
    if (countTime >= 0) {
        if ([self.delegate respondsToSelector:@selector(timerDidStart:withTime:)]) {
            [self.delegate timerDidStart:self withTime:countTime];
        }
        
        countTime --;
    }
    else{
        if (countTimer != nil) {
            [countTimer invalidate];
            countTimer = nil;
           
            if ([self.delegate respondsToSelector:@selector(timerDidFinish:)]) {
                [self.delegate timerDidFinish:self];
            }
            
            [CTDebugManager showDebugLogInfo:@"获取验证码timer移除"];
        }
    }
}



#pragma mark - net request for get verification code

-(void)sendSmsMessage:(NSString *)phoneNumber area:(NSString *)zone
{
    [SMS_SDK getVerificationCodeBySMSWithPhone:phoneNumber zone:zone result:^(SMS_SDKError *error) {
        
        if (error != nil) {
            if ([self.delegate respondsToSelector:@selector(sendMessageFailed:)]) {
                [self.delegate sendMessageFailed:self];
            }
        }
        else
        {
//            if ([self.delegate respondsToSelector:@selector(sendMessageSuccess:)]) {
//                [self.delegate sendMessageSuccess:self];
//            }
        }
    }];
    
}



-(void)verificationRequest:(CTVerificationRequestItem *)item verifyCode:(NSString *)code successCompletionHandler:(requestSuccessBlock)successBlock failedHandler:(requestFailedBlock)failedBlock
{
    
    [SMS_SDK commitVerifyCode:code result:^(enum SMS_ResponseState state) {
        if (state == SMS_ResponseStateSuccess) {
            
            
            NSMutableDictionary * param = [NSMutableDictionary dictionaryWithCapacity:0];
            @try {
                [param setObject:item.mobile forKey:@"mobile"];
            }
            @catch (NSException *exception) {
                
            }
            
            [CTRequestUtil sendAsyGetRequest:CT_URL_ACCOUNTS_VALIDATE(version) withParam:param withCompletionSuccessHandler:^(NSData *data) {
                BOOL isParserSuccess = [self parserData:data];
                if (isParserSuccess == YES) {
                    successBlock();
                }
                else
                {
                    failedBlock();
                }
                
            } withFailedHandler:^(NSError *error) {
                failedBlock();
            }];
            
        }
        else
        {
            failedBlock();
        }
    }];
}




#pragma mark - data parser -

-(BOOL)parserData:(NSData *)resultData
{
    
    BOOL isParserSuccess = NO;
    
    @try {
        
        NSError * error;
        
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:resultData
                         options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                NSString * errCode = [NSString stringWithFormat:@"%@",(NSString *)[deserializedDictionary objectForKey:@"error_code"]];
                if ([errCode isEqualToString:@"0"]) {
                    
                    isParserSuccess = YES;
                    
                    NSDictionary * infoDic = [deserializedDictionary objectForKey:@"info"];
                    NSString * mobileStr = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"mobile"]];
                    NSString * createdStr = [NSString stringWithFormat:@"%@",[infoDic objectForKey:@"created"]];
                    
                    //1 注册 0未注册
                    [CTFile cacheFile:createdStr
                             fileName:@"userCreated.text"
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                    
                    //user phonenumber
                    [CTFile cacheFile:mobileStr
                             fileName:@"userPhoneNumber.text"
                              saveDoc:CTFileDocDocuments
                             savePath:@"user"];
                }
            }
        }
        else
        {
            [CTDebugManager showErrorLogInfo:@"解析验证数据错误！"];
        }
    }
    @catch (NSException *exception) {
        [CTDebugManager showErrorLogInfo:@"解析验证数据错误！"];
    }
    
    return isParserSuccess;
    
}

@end
